package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
@Slf4j
public class SupplyTaskHandler implements MsgHandler {

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String jsonMsg) throws IOException {
        try {
            //解析数据
            SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);

            if (supplyContract == null) return;
            //售货机信息
            VmVO vmInfo = vmService.getVMInfo(supplyContract.getInnerCode());

            //找到要指派的用户
            int leastUser = taskService.getLeastUser(vmInfo.getRegionId(), false);

            TaskViewModel taskViewModel = new TaskViewModel();
            taskViewModel.setCreateType(0);
            taskViewModel.setInnerCode(vmInfo.getInnerCode());
            taskViewModel.setAssignorId(leastUser);
            taskViewModel.setUserId(leastUser);
            taskViewModel.setAssignorId(0);//用户创建人id
            taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
            taskViewModel.setDesc(jsonMsg);


            List<SupplyChannel> supplyChannels = supplyContract.getSupplyData();

            //工单详情(只有补货工单才涉及)
            //填充数据
            List<TaskDetailsViewModel> detailsViewModels = supplyChannels.stream().map(
                    s -> {
                        TaskDetailsViewModel detailsViewModel = new TaskDetailsViewModel();
                        detailsViewModel.setChannelCode(s.getChannelId());
                        detailsViewModel.setExpectCapacity(s.getCapacity());
                        detailsViewModel.setSkuId(s.getSkuId());
                        detailsViewModel.setSkuImage(s.getSkuImage());
                        detailsViewModel.setSkuName(s.getSkuName());
                        return detailsViewModel;
                    }
            ).collect(Collectors.toList());

            taskViewModel.setDetails(detailsViewModels);

            taskService.createTask(taskViewModel);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("创建自动补货工单出错" + e.getMessage());
        }
    }
}